import { createElement, TableHTMLAttributes, type FC } from 'react';
import classNames from 'classnames';

import { tableDefaultProps } from './defaultProps';
import type { TableOptions } from './type';
import TableHeader from './TableHeader';
import TableBody from './TableBody';
import TableFooter from './TableFooter';
import TableRow from './TableRow';
import TableHeaderCell from './TableHeaderCell';
import TableCell from './TableCell';
import numberToWord from '../_util/numberToWord';

export interface TableProps extends TableOptions, Omit<TableHTMLAttributes<HTMLTableElement>, 'color'> {}

interface TableInterface extends FC<TableProps> {
  Header: typeof TableHeader;
  HeaderCell: typeof TableHeaderCell;
  Body: typeof TableBody;
  Footer: typeof TableFooter;
  Row: typeof TableRow;
  Cell: typeof TableCell;
}

const Table: TableInterface = (props) => {
  const {
    className,
    celled,
    padded,
    compact,
    definition,
    structured,
    fixed,
    singleLine,
    unstackable,
    stackable,
    selectable,
    striped,
    textAlign,
    verticalAlign,
    basic,
    collapsing,
    columns,
    color,
    inverted,
    sortable,
    size,
    scrolling,
    stuck,
    children,
    forwardedRef,
    ...tableProps
  } = props;

  return createElement(
    'table',
    {
      ref: forwardedRef,
      className: classNames(
        'ui',
        color,
        { fixed, 'single line': singleLine, celled, definition, structured, unstackable, selectable },
        stackable,
        { stackable, striped, sortable },
        padded,
        { padded },
        compact,
        { compact },
        textAlign,
        { aligned: textAlign },
        verticalAlign,
        { aligned: verticalAlign },
        basic,
        { basic, collapsing },
        numberToWord(columns),
        { column: columns, inverted },
        size,
        stuck,
        { stuck },
        scrolling,
        { scrolling },
        'table',
        className,
      ),
      ...tableProps,
    },
    children,
  );
};

Table.displayName = 'Table';
Table.defaultProps = tableDefaultProps;

Table.Header = TableHeader;
Table.HeaderCell = TableHeaderCell;
Table.Body = TableBody;
Table.Footer = TableFooter;
Table.Row = TableRow;
Table.Cell = TableCell;

export default Table;
